package com.zyx.xunyilu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyx.xunyilu.config.jwt.JWTUtils;
import com.zyx.xunyilu.entity.Article;
import com.zyx.xunyilu.entity.CommentArticle;
import com.zyx.xunyilu.entity.User;
import com.zyx.xunyilu.mapper.ArticleMapper;
import com.zyx.xunyilu.mapper.CommentArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName: CommentArticleService
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/12/16 21:43
 */
@Service
public class CommentArticleService {

    @Autowired
    UserService userService;

    @Autowired
    CommentArticleMapper commentArticleMapper;

    @Autowired
    ArticleMapper articleMapper;

    @Autowired
    JWTUtils jwtUtils;

    public CommentArticle insert(CommentArticle commentArticle, String token) throws Exception {
        User user = null;
        try {
            String username = jwtUtils.getUsername(token);
            user = userService.findUserByName(username);
        } catch (Exception e) {
            throw e;
        }
        commentArticle.setPersonId(user.getId());
        commentArticleMapper.insert(commentArticle);
        Integer id = commentArticle.getId();
        return this.selectById(id);
    }

    public IPage<CommentArticle> selectByCId(Integer cId, Integer page, Integer size) {
        return commentArticleMapper.selectPage(new Page<>(page, size),
                new QueryWrapper<CommentArticle>().eq("c_id", cId).orderByDesc("time"));
    }

    public IPage<CommentArticle> selectArticleCommentPage(Integer articleId, Integer page, Integer pageSize) {
        return commentArticleMapper.selectPage(new Page<>(page, pageSize),
                new QueryWrapper<CommentArticle>().eq("p_id", articleId).isNull("c_id").orderByDesc("time"));
    }

    public IPage<Article> selectMyCommonArticlePage(Integer userId, Integer page, Integer pageSize) {
        List<CommentArticle> person_id = commentArticleMapper.selectList(new QueryWrapper<CommentArticle>().eq("person_id", userId));
        Set<Integer> pIdSet = new HashSet<>();
        person_id.forEach(t -> {
            pIdSet.add(t.getPId());
        });
        IPage<Article> selectPage = articleMapper.selectPage(new Page<>(page, pageSize), new QueryWrapper<Article>().in("id", pIdSet));
        return selectPage;
    }

    public CommentArticle selectById(Integer id) {
        return commentArticleMapper.selectById(id);
    }

}
